﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Reflection;

namespace Sbook.Library
{
    public class m_Library
    {
        public T ConvertToObject<T>(DataRow row)
        {
            //Lay type cua T
            Type type = typeof(T);
            //Goi ham khoi tao contractor khong tham so=>truyen 1 mang type[] {},gia tri truyen vao cua Type la 1 mang object[] {}
            T o = (T)type.GetConstructor(new Type[] { }).Invoke(new object[] { });
            //Lay cac property
            PropertyInfo[] properties = type.GetProperties();
            //chay vong lap
            for (int i = 0; i < properties.Length; i++)
            {
                //Neu cot khong chua properties name thi quay lai
                if (!row.Table.Columns.Contains(properties[i].Name))
                    continue;

                //Neu cot chua name ma khong chua gia tri thi quay lai
                if (row[properties[i].Name].Equals(DBNull.Value))
                    continue;

                //neu co thi set gia tri cho object
                properties[i].SetValue(o, Convert.ChangeType(row[properties[i].Name], properties[i].PropertyType), null);
            }
            //Tra ve doi tuong kieu T
            return o;
        }

        //Ham Convert 1 table thanh kieu List<object>
        public List<T> GetToList<T>(DataTable tbl)
        {
            List<T> list = new List<T>();
            Type type = typeof(T);
            T o;
            foreach (DataRow row in tbl.Rows)
            {
                o = this.ConvertToObject<T>(row);
                list.Add(o);
            }
            return list;
        }
        //Ham Fomat Product
        
    }
}